//新版基础函数
var f = {
  init: function () {
    log("程序初始化")
  },
  //post
  post: function (url, data) {
    var res = http.post(url, data);
    var data = res.body.string();
    if (data) {
      // log(data);
      return data;
    }
  },
  //get
  get: function (url) {
    var res = http.get(url);
    var data = res.body.string();
    if (data) {
      return data;
    }
  },
  //读取本地数据
  getLocal: function (name, key) {
    const storage = storages.create(name);  //创建storage对象
    if (storage.contains(key)) {
      return storage.get(key);
    };
    //默认返回undefined
  },
  //基础函数
  active: function (pkg, n) {
    if (!n) { n = 5 }
    if (currentPackage() == pkg) {
      log("应用在前端");
      return true;
    } else {
      log("启动一次应用");
      app.launch(pkg);
      sleep(1000)
      f.ms({ "textMatches": "允许|始终允许" }, true)
      sleep(1000 * n)
    }
  },
  //准备点击
  click: function (x, y, sleeptime, name) {
    if (!sleeptime) { sleeptime = 1 }
    if (name) {
      log('准备点击->' + name, "x:", x, "y:", y);
    } else {
      log('准备点击坐标->', "x:", x, "y:", y);
    }
    if (x > 0 && y > 0) {
      threads.start(function () {
        //在新线程执行的代码
        click(x, y);
      });
      // click(x,y);
      sleep(sleeptime * 1000);
      return true
    } else {
      log('坐标错误');
    }
  },
  //点击obj
  clickObj: function (obj, sleeptime, name) {
    if (!sleeptime) { sleeptime == 1 }
    log(name ? ("准备点击对象->" + name) : "点击未命名对象")
    x = obj.bounds().centerX()
    y = obj.bounds().centerY()
    return f.click(x, y, sleeptime, name)
  },
  //穿透点击
  clickTrue: function (obj, sleeptime, name, lun) {
    sleeptime ? sleeptime : 1
    let result = false;
    lun ? lun : 3
    for (let i = 0; i < lun; i++) {
      if (obj && obj.clickable()) {
        obj.click();
        log(name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象")
        result = true
        break
      }
      obj = obj.parent()
    }
    if (result) { sleep(sleeptime * 1000) }
    return result
  },
  //正则点击
  ms: function (obj, clicks, sleeptimes, name, findtime, lun) {
    if (!sleeptimes) { sleeptimes = 1 }
    if (!findtime) { findtime = 200 }
    if (!lun) { lun = 3 }

    var txt = '';
    for (let key in obj) {
      if (key.search("Matches") > 0) {
        eval("var matches = /" + obj[key] + "/")
        txt = txt + key + '(' + matches + ').'
      } else if (key == 'boundsInside') {
        txt = txt + key + '(' + obj[key] + ').'
      } else {
        txt = txt + key + '("' + obj[key] + '").'
      }
    }
    var txt = "let objs = " + txt + "findOne(" + findtime + ");"
    log(txt)
    eval(txt)
    if (objs) {
      log('找到==>' + objs.text() || objs.desc() || objs.id() || objs.className())
      if (clicks) {
        name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
        if (lun < 1 || !f.clickTrue(objs, sleeptimes, name, lun)) {
          log('准备坐标点击')
          return f.clickObj(objs, sleeptimes, name);
        }
      }
      return true;
    }
  },
  rd: function (min, max) {
    if (min <= max) {
      return random(min, max)
    } else {
      return random(max, min)
    }
  },
  moveTo: function (x, y, x1, y1, times) {
    swipe(x, y, x1, y1, times);
    sleep(1000);
  },
  getTextById: function (idstr) {
    try {
      return id(idstr).findOne(200).text()
    } catch (e) {
      log(e)
    }
  }
}
f.init()


//批查打印app参数
function printAll(ways) {
  if (!ways) {
    ways = 'className'
  }
  if (ways = 'className') {
    var all_Info = classNameMatches(/.*/).find();
  } else
    if (ways == 'text') {
      var all_Info = textMatches(/.*/).find();
    } else
      if (ways == 'id') {
        var all_Info = idMatches(/.*/).find();
      } else {
        eval('var all_Info = ' + ways + '.find();')
      }

  if (all_Info) {
    for (var i = 0; i < all_Info.length; i++) {
      var d = all_Info[i];
      log(i, d.id(), d.text(), "desc:" + d.desc(), '"className":"' + d.className() + '"',
        "clickable->" + d.clickable(), 'selected->' + selected(), "depth->" + d.depth(),
        d.bounds().centerX(), d.bounds().centerY())
    }
  } else {
    log('没有找到任何相关的节点')
  }
}


// printAll()



//河马ip
function hmip() {
  var result = shell("ipclient faa31f81bfea4124995972d5dc016b57 1", true);
  // console.show();
  // log(result);
  if (result.code == 0) {
    toastLog("vpn 执行成功");
    return true
  } else {
    toastLog(result)
    toastLog("vpn 执行失败！请到控制台查看错误信息");
  }
}


function hmip_x() {
  var result = shell("ipclient faa31f81bfea4124995972d5dc016b57 0", true);
  // console.show();
  // log(result);
  if (result.code == 0) {
    toastLog("vpn 执行成功");
    return true
  } else {
    toastLog(result)
    toastLog("vpn 执行失败！请到控制台查看错误信息");
  }
}



//设备大师
function sbds() {
  let fix = false
  var start = false
  var timeLine = new Date().getTime()
  while (new Date().getTime() - timeLine < 5 * 60 * 1000) {

    if (f.active(appinfo.sbdsbid, 5)) {

      if (fix && f.ms({ "text": "修改设备" }, false, rd(2, 3))) {
        return true
      } else
        if (f.ms({ "text": "修改设备" }, true, rd(2, 3))) {
          start = true;
        } else if (start && f.ms("id", "brand", true, rd(2, 3))) {

          var phonelist = ["XIAOMI", "HUAWEI", "SAMSUNG", "HONOR", "vivo"]
          if (f.ms({ "text": phonelist[rd(0, 4)], "depth": 4 }, true, rd(1, 2))) {
            f.ms("text", "下一步", true, rd(2, 3))
          } else {
            f.ms("id", "back", true, rd(2, 3))
          }

        } else if (start && f.ms("text", "立即清理", false, rd(2, 3))) {
          f.ms("text", "以吾之力", true, 1)
          f.ms("text", "QQ浏览器", true, 1)

          if (f.ms("text", "立即清理", true, rd(10, 15))) {
            fix = true
          }
        } else {
          f.ms("id", "back", true, rd(2, 3))
        }
    }
    sleep(1000);
  }
}


//设备大师
function sbdsJk() {

  // f.active(appinfo.sbdsbid, 5)
  var result = shell("setphone", true);

  // eval( 'var result = shell("setphone -m vivo -b vivo -o ' + phoneMode[rd(0,5)] +'" ,true)'  )
  // var result = shell("setphone -m vivo -b vivo -o Y85A" ,true);
  // console.show();
  log(result);
  if (result.code == 0) {
    toastLog("一键新机 执行成功")
  } else {
    toastLog("一键新机 执行失败！请到控制台查看错误信息")
  }

  eval('var result = shell("pm clear ' + appinfo.bid + '",true)')
  // eval( 'var result = shell("pm clear '+ appinfo.llq +'",true)'  )
  // var result = shell("pm clear com.youxiang.soyoungapp",true)
  log(result);
  if (result.code == 0) {
    toastLog("一键清理 执行成功");
    return true
  } else {
    toastLog("一键清理 执行失败！请到控制台查看错误信息");
  }


  recents();
  sleep(3000)

  if (f.ms({ "descMatches": "移除设备大师.*" }, true, 3)) {
    return true
  }
}

//设备大师参数信息
function getsbds() {
  let fix = false;
  var start = false;
  var timeLine = new Date().getTime();
  while (new Date().getTime() - timeLine < 3 * 60 * 1000) {
    if (f.active(appinfo.sbdsbid, 3)) {

      if (f.ms({ "text": "当前设备" })) {
        log("设备信息界面");
        appinfo.imei = id("imei").findOne(100).text();
        appinfo.oaid = id("android_id").findOne(100).text();
        appinfo.model = id("phone_model").findOne(100).text();
        appinfo.brand = id("phone_brand").findOne(100).text();

        // console.show()
        log(appinfo);
        home()
        sleep(1000)
        return true;
      }

    }
  }
}





//上传idfa
function Idfa(other) {
  let postArr = {};
  postArr['service'] = 'Idfa.idfa';
  postArr['name'] = appinfo.name;
  postArr['idfa'] = appinfo.device.android_id || device.getAndroidId() || new Date();
  postArr['phone'] = appinfo.phone
  postArr['phoneos'] = appinfo.model || device.model
  postArr['password'] = appinfo.brand || device.brand
  // postArr['account'] = appinfo.token
  postArr['other'] = other ? other : "成功";
  let data = f.post("http://wenfree.cn/api/Public/idfa/", postArr);
  log(data)
  toastLog("上传成功")
}

//上传idfa
function Idfaqw(d) {
  let postArr = {};
  postArr['service'] = 'Idfa.idfa';
  postArr['name'] = appinfo.name;
  postArr['idfa'] = d.android_id
  // postArr['account'] = appinfo.token
  postArr['other'] = d.phone_brand
  postArr['device'] = JSON.stringify(d)
  let data = f.post("http://wenfree.cn/api/Public/idfa/", postArr);
  log(data)
  toastLog("上传成功")
}

//上传idfa
function Idfa_error(other) {
  let postArr = {};
  postArr['service'] = 'Idfa.idfa';
  postArr['name'] = appinfo.name + '错误';
  postArr['idfa'] = appinfo.imei || device.getIMEI() || new Date();
  postArr['appid'] = appinfo.oaid || device.getAndroidId()
  postArr['phoneos'] = appinfo.model || device.model
  postArr['password'] = appinfo.brand || device.brand
  // postArr['account'] = appinfo.token
  postArr['other'] = other ? other : "成功";
  let data = f.post("http://wenfree.cn/api/Public/idfa/", postArr);
  log(data)
  toastLog("上传成功")
}

//上传idfa
function total() {
  let postArr = {};
  postArr['service'] = 'App.Total.Record';
  postArr['name'] = appinfo.name
  let data = f.post("http://api.wenfree.cn/", postArr);
  log(data)
  toastLog("统计成功")
}

function Mock() { }

Mock.mobile_prefix = ["134", "135", "136", "137", "138", "139", "150", "151", "152", "157", "158", "159", "130", "131", "132", "155", "156", "133", "153"]
Mock.numeric = "0123456789";
Mock.random = function (len, list) {
  if (len <= 1) { len = 1; }
  var s = "";
  var n = list.length;
  if (typeof list === "string") {
    while (len-- > 0) {
      s += list.charAt(Math.random() * n)
    }
  } else if (list instanceof Array) {
    while (len-- > 0) {
      s += list[Math.floor(Math.random() * n)]
    }
  }
  return s;
}
Mock.getMobile = function () {
  return Mock.random(1, Mock.mobile_prefix) + Mock.random(8, Mock.numeric);
}



function checkIp() {
  url = "http://wenfree.cn/api/Public/idfa/?service=Ip.Checkip&ip=&name=" + appinfo.name
  log(url)
  r = f.post(url, {})
  log(r)
  if (r) {
    r = JSON.parse(r)
    if (r.data.state == "ok") {
      toastLog(r.data.ip + "可以使用")
      return true
    }
  }
}

function openUrl() {
  url = "https://wqs.jd.com/downloadApp/downloadLiteApp.html?channel=superjd-m-qiqitest-facaiwabao"
  app.openUrl(url)
  sleep(1000)
  let i = 0
  while (i < 30) {
    // f.ms({"textMatches":"QQ浏览器"},true,2)
    f.ms({ "textMatches": "始终" }, true, 2)
    f.ms({ "textMatches": "知道了" }, true, 2)
    f.ms({ "textMatches": "允许" }, true, 2)
    f.ms({ "textMatches": "允许" }, true, 2)
    if (f.ms({ "textMatches": "Android版本下载" }, true, f.rd(5, 6))) {
      if (f.ms({ "textMatches": "直接下载|普通下载" }, true, f.rd(4, 6))) {
        eval('var result = shell("pm clear ' + appinfo.llq + '",true)')
      }
      return true
    }
    i++
    sleep(1000)
  }
}




//光子ip
function gz_ip() {

  var hostIpText = "未取";
  var timeLine = new Date().getTime();
  while (new Date().getTime() - timeLine < 3 * 60 * 1000) {
    if (f.active(appinfo.gzbid, 3)) {

      f.ms({ "text": "确定" }, true, 2)
      if (f.ms({ "id": "username" })) {
        setText(0, "wenfree")
        setText(1, "Aa112211")
        f.ms({ "text": "自动登录", "checked": false }, true, 1)
        f.ms({ "text": "立即登录" }, true, 3)
      }

      if (hostIpText == "未取") {
        hostIpText = id("hostIpText").findOne(1000).text()
        log("hostIpText", hostIpText)
        if (f.ms({ "text": "切换节点" }, true, 2)) {
          return true
        }
      } else {
        newHostIP = id("hostIpText").findOne(1000)
        if (newHostIP) {
          log(newHostIP.text(), "newHostIP")
          if (newHostIP.text() != hostIpText) {
            return true
          }
        }
      }

      sleep(1000)
    }
  }
}


function gzjd() {

  let i = 60
  while (i > 0) {
    f.active(appinfo.gzbid, 5)

    f.ms({ "text": "立即登录" }, true, 3)

    if (f.ms({ "id": "vpnSwitch" }, true, 1)) {
      ip = id("hostIpText").findOne(200)
      if (ip) {
        ip_ = ip.text()

        log(ip)
        return true
      }
    }
    sleep(1000)
  }

}

// 正式开始编代码
var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(), currentActivity(), width, height]);
var appinfo = {}
appinfo.name = "马小象写字";
appinfo.bid = "com.mobcoreapp";
appinfo.llq = "com.tencent.mtt";
appinfo.gzbid = "com.deruhai.guangzi";
appinfo.sbdsbid = "com.blue.backup";
appinfo.device = {}

info = {};
info.h5 = "https://wqs.jd.com/downloadApp/downloadLiteApp.html?channel=superjd-m-qiqitest-facaiwabao"
info.url = "https://apk.360buyimg.com/build-cms/V3.8.18-2318-800001483-superjd-m-qiqitest-facaiwabao-32bit.apk"
info.openFrist = true

function sbzs() {
  var phones = [
    'samsung',
    'Xiaomi',
    'Sony',
    'OPPO',
    'XIAOMI',
    'vivo',
    'HUAWEI',
    'HONOR'
  ]

  let i = 0
  let key = false
  while (i < 30) {
    f.active(appinfo.sbdsbid, 5)
    f.ms({ "text": "一键新机" }, true, 2)

    if (f.ms({ "text": "当前设备" }, false, 2)) {

      if (key) {
        sleep(5000)
        return true
      }

      var ids = [
        'phone_vendor',
        'phone_brand',
        'phone_model',
        'phone_serial_number',
        'android_id',
        'imsi',
        'wifi_mac',
        'op_name',
        'btaddr',
        'displayid',
        'baseband',
      ]

      appinfo.device = {}
      for (let i = 0; i < ids.length; i++) {
        appinfo.device[ids[i]] = f.getTextById(ids[i])
      }

      f.ms({ "text": "修改设备信息" }, true, 2)
    }
    else if (f.ms({ "text": "设备属性设置" }, false, 2)) {
      f.ms({ "text": "指定机型" }, true, 2)
      f.ms({ "id": "brand" }, true, 2)



      f.ms({ "text": phones[f.rd(0, 7)], 'id': 'brand' }, true)
      f.ms({ "text": "下一步" }, true, 2)


    } else if (f.ms({ "text": "立即清理" }, false, 2)) {
      key = true
      f.ms({ "text": "河小象写字" }, true, 2)
      f.ms({ "text": "立即清理" }, true, 2)
    }

    f.ms({ "text": phones[f.rd(0, 7)], 'id': 'brand' }, true)
    sleep(1000)
  }
}

function main() {
  // f.active(appinfo.bid, 5)
  let i = 60
  while (i > 0) {
    f.active(appinfo.bid, 5)


    //河小象写字
    f.ms({ "text": "监护人已同意" }, true, 2)
    f.ms({ "text": "同意并继续" }, true, 2)
    f.ms({ "id": "iv_agree_login_box" }, true, 2)
    f.ms({ "text": "免费" }, true, 2)
    if (f.ms({ "text": "请输入手机号" }, true, 2)) {
      appinfo.phone = Mock.getMobile()
      log('手机号', appinfo.phone)
      setText(0, appinfo.phone)
    }

    f.ms({ "text": "获取验证码" }, true, 3)
    if (f.ms({ "textMatches": ".*后重试" })) {
      return true
    }


    i--
    sleep(1000)
  }
}

function all() {
  while (true) {

    try {

      if (sbzs()) {

        if (main()) {
          Idfa('青蛙')
        }

      }

    } catch (e) {
      log(e)
    }

  }
}

console.show()
all()


// openUrlByQQ()